package com.wisdytech.linkdcs.partLife.service.impl;

import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.linkdcs.partLife.dao.*;
import com.wisdytech.linkdcs.partLife.dto.PartStorageSaveDTO;
import com.wisdytech.linkdcs.partLife.model.*;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.partLife.dto.PartRepSearchDTO;
import com.wisdytech.linkdcs.partLife.dto.PartReplaceDTO;
import com.wisdytech.linkdcs.partLife.service.IPartReplaceService;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wisdytech.linkdcs.partLife.dto.PartStorageSaveDTO;
import javax.annotation.Resource;

import com.wisdytech.linkdcs.partLife.service.IPartStorageRecordService;
import com.wisdytech.linkdcs.system.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  设备备件更换服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-06-05
 */
@Service("iPartReplaceService")
@Transactional
public class PartReplaceServiceImpl extends BaseService<IPartReplaceDao, PartReplace> implements IPartReplaceService {
	
    /**
     * 注入更换dao
     */
    @Resource
    private IEqEquipmentDao iEqEquipmentDao;
    /**
     * 注入设备dao
     */
    @Resource
    private IKeyPartDao iKeyPartDao;
    /**
     * 注入设备dao
     */
    @Resource
    private IPartReplaceDao iPartReplaceDao;

    /**
     * 注入备件信息管理dao
     */
    @Resource
    private IPartDao iPartDao;
    /**
     * 注入备件信息管理dao
     */
    @Resource
    private IPartStorageRecordDao iPartStorageRecordDao;
    @Resource
    private IModelPartDao iModelPartDao;
    /**
     * 注入备件信息iPartService
     */
    @Autowired
    @Qualifier("iPartStorageRecordService")
    private IPartStorageRecordService iPartStorageRecordService;
	@Override
	public List<Equipment> listAllEquipAndPart(String equipName) {
		 List<Equipment> equipList = iEqEquipmentDao.listAllEquipAndPart(equipName);
		return equipList;
	}
	@Override
	public PageInfo<PartReplace> listPartRepByFilter(String equipId, Filter filter) {
        if(StringUtils.isBlank(equipId))
            return new PageInfo<>(new ArrayList<>());
        List<PartReplace> list = this.beforeList(IPartReplaceDao.class,filter).listPartRepByFilter(equipId);
        PageInfo<PartReplace> page = new PageInfo<>(list);
        return page;
	}
	@Override
	public PartReplace getSeriByEquipId(String equipId) {
		PartReplace partReplace = iPartReplaceDao.getSeriByEquipId(equipId);
		return partReplace;
	}
	@Override
	public void savePartReplace(PartReplaceDTO partReplacedto) {
		//判断是否为关键备件
		if(partReplacedto.getKeyPartFlag().equals("0")) {
			//插入备件更换信息
			PartReplace partReplace = new PartReplace();
			partReplace.setPkId(BaseUtil.getUUID());
			partReplace.setEquipId(partReplacedto.getEquipId());
			partReplace.setnSerialNum(partReplacedto.getnSerialNum());
			//判断是否为第一次更换
//			if(StringUtils.isEmpty(partReplacedto.getoSerialNum())) {
//				partReplace.setoSerialNum(partReplacedto.getnSerialNum());
//			}
			if(StringUtils.isNoneEmpty(partReplacedto.getoSerialNum())) {
				partReplace.setoSerialNum(partReplacedto.getoSerialNum());
			}
			partReplace.setRepUser(partReplacedto.getRepUser());
			partReplace.setRepReason(partReplacedto.getRepReason());
			partReplace.setRepNum(partReplacedto.getRepNum());
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date0;
			try {
					date0 = df.parse(partReplacedto.getRepDate());
					partReplace.setRepDate(date0);
			} catch (ParseException e) {
				e.printStackTrace();
			}  
			partReplace.setRemark(partReplacedto.getRemark());
			partReplace.setPartId(partReplacedto.getPartId());
			partReplace.setCreateDate(new Date());
			//保存更换信息
			iPartReplaceDao.insert(partReplace);
			KeyPart keyPart = new KeyPart();
			keyPart.setPkId(partReplacedto.getnSerialNum());
			//将关键备件改为使用中
			keyPart.setStatus(2.0);
			//获取即将更改的关键备件
			if(partReplacedto.getnSerialNum()!=null && partReplacedto.getnSerialNum()!="") {
				KeyPart nowkeyPart = iKeyPartDao.selectById(partReplacedto.getnSerialNum());
				if(nowkeyPart.getReplaceNum()==null || nowkeyPart.getReplaceNum()==0) {
					int i = 0;
					keyPart.setReplaceNum(i+1);
				}else {
					keyPart.setReplaceNum(nowkeyPart.getReplaceNum()+1);
				}
			}

			iKeyPartDao.updateById(keyPart);
			//获取原备件,并更改状态
			if(StringUtils.isNoneEmpty(partReplacedto.getoSerialNum())) {
				KeyPart oldkeyPart = iKeyPartDao.selectById(partReplacedto.getoSerialNum());
				oldkeyPart.setStatus(partReplacedto.getStatus());
				iKeyPartDao.updateById(oldkeyPart);
			}

			//新备件自动进行出库操作
            SysUser sysUser = BaseUtil.getCurrentUser();
            String userId = sysUser.getPkId();
            PartStorageSaveDTO pDTO = new PartStorageSaveDTO();
			pDTO.setStorageNum(1.0);//数量，关键备件默认为1
            KeyPart kPart = null;
            if(partReplacedto.getnSerialNum()!=null && partReplacedto.getnSerialNum()!="") {
                kPart = iKeyPartDao.selectById(partReplacedto.getnSerialNum());
            }
            pDTO.setPartId(kPart.getPartId());//更换备件的id
            pDTO.setPickUser(partReplacedto.getRepUser());//领料人
            pDTO.setRemark("备件更换出库");
            pDTO.setStorageTime(partReplacedto.getRepDate());
            try {
                this.iPartStorageRecordService.savepartStorage(pDTO,userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
			//插入备件更换信息
			PartReplace partReplace = new PartReplace();
			partReplace.setPkId(BaseUtil.getUUID());
			partReplace.setEquipId(partReplacedto.getEquipId());
			partReplace.setRepUser(partReplacedto.getRepUser());
			partReplace.setRepReason(partReplacedto.getRepReason());
			partReplace.setRepNum(partReplacedto.getRepNum());
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date0;
			try {
					date0 = df.parse(partReplacedto.getRepDate());
					partReplace.setRepDate(date0);
			} catch (ParseException e) {
				e.printStackTrace();
			}  
			partReplace.setRemark(partReplacedto.getRemark());
			partReplace.setPartId(partReplacedto.getPartId());
			partReplace.setCreateDate(new Date());
			//保存更换信息
			iPartReplaceDao.insert(partReplace);
            //新备件自动进行出库操作
            SysUser sysUser = BaseUtil.getCurrentUser();
            String userId = sysUser.getPkId();
            PartStorageSaveDTO pDTO = new PartStorageSaveDTO();
            pDTO.setStorageNum(partReplacedto.getRepNum());
            ModelPart mp = iModelPartDao.selectById(partReplacedto.getPartId());
            pDTO.setPartId(mp.getPartId());//更换备件的id
            pDTO.setPickUser(partReplacedto.getRepUser());//领料人
            pDTO.setRemark("备件更换出库");
            pDTO.setStorageTime(partReplacedto.getRepDate());
            try {
                this.iPartStorageRecordService.savepartStorage(pDTO,userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}

	}

    @Override
	public PageInfo<PartReplace> listPartRepAllByFilter(PartRepSearchDTO repSearchDTO, Filter filter) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("equipCode", repSearchDTO.getEquipCode());
        queryMap.put("equipName",repSearchDTO.getEquipName());
        queryMap.put("partName", repSearchDTO.getPartName());
        queryMap.put("oSerialNum", repSearchDTO.getoSerialNum());
        queryMap.put("startTime", repSearchDTO.getStartTime());
        queryMap.put("endTime", repSearchDTO.getEndTime());
        queryMap.put("shortcutTime", repSearchDTO.getShortcutTime());//快捷时间
        List<PartReplace> list = this.beforeList(IPartReplaceDao.class,filter).listPartRepAllByFilter(queryMap);
        PageInfo<PartReplace> page = new PageInfo<>(list);
		return page;
	}
	@Override
	public void savePartReplaceTemp(PartReplaceDTO partReplacedto) {
		//判断是否为关键备件
		if(partReplacedto.getKeyPartFlag().equals("0.0")) {
			//插入备件更换信息
			PartReplace partReplace = new PartReplace();
			partReplace.setPkId(BaseUtil.getUUID());
			partReplace.setEquipId(partReplacedto.getEquipId());
			partReplace.setnSerialNum(partReplacedto.getnSerialNum());
			//判断是否为第一次更换
//			if(StringUtils.isEmpty(partReplacedto.getoSerialNum())) {
//				partReplace.setoSerialNum(partReplacedto.getnSerialNum());
//			}
			if(StringUtils.isNoneEmpty(partReplacedto.getoSerialNum())) {
				partReplace.setoSerialNum(partReplacedto.getoSerialNum());
			}
			partReplace.setRepUser(partReplacedto.getRepUser());
			partReplace.setRepReason(partReplacedto.getRepReason());
			partReplace.setRepNum(partReplacedto.getRepNum());
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date0;
			try {
				if(partReplacedto.getRepDate()==null) {
					partReplace.setRepDate(new Date());
				}else {
					date0 = df.parse(partReplacedto.getRepDate());
					partReplace.setRepDate(date0);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}  
			partReplace.setCreateDate(new Date());
			partReplace.setRemark(partReplacedto.getRemark());
			partReplace.setPartId(partReplacedto.getPartId());
			//保存更换信息
			iPartReplaceDao.insert(partReplace);
			KeyPart keyPart = new KeyPart();
			keyPart.setPkId(partReplacedto.getnSerialNum());
			//将关键备件改为使用中
			keyPart.setStatus(2.0);
			//获取即将更改的关键备件
			if(partReplacedto.getnSerialNum()!=null && partReplacedto.getnSerialNum()!="") {
				KeyPart nowkeyPart = iKeyPartDao.selectById(partReplacedto.getnSerialNum());
				if(nowkeyPart.getReplaceNum()==null || nowkeyPart.getReplaceNum()==0) {
					int i = 0;
					keyPart.setReplaceNum(i+1);
				}else {
					keyPart.setReplaceNum(nowkeyPart.getReplaceNum()+1);
				}
				iKeyPartDao.updateById(keyPart);
			}

			//获取原备件,并更改状态
			if(StringUtils.isNoneEmpty(partReplacedto.getoSerialNum())) {
				KeyPart oldkeyPart = iKeyPartDao.selectById(partReplacedto.getoSerialNum());
				oldkeyPart.setStatus(partReplacedto.getStatus());
				iKeyPartDao.updateById(oldkeyPart);
			}
            //新备件自动进行出库操作
            SysUser sysUser = BaseUtil.getCurrentUser();
            String userId = sysUser.getPkId();
            PartStorageSaveDTO pDTO = new PartStorageSaveDTO();
            pDTO.setStorageNum(1.0);//数量，关键备件默认为1
            KeyPart kPart = null;
            if(partReplacedto.getnSerialNum()!=null && partReplacedto.getnSerialNum()!="") {
                kPart = iKeyPartDao.selectById(partReplacedto.getnSerialNum());
            }
            pDTO.setPartId(kPart.getPartId());//更换备件的id
            if(StringUtils.isNotEmpty(partReplacedto.getDealUser())){
                pDTO.setPickUser(partReplacedto.getDealUser());//故障处理人及为领料人
            }else {
                pDTO.setPickUser(partReplacedto.getRepUser());//领料人
            }
            pDTO.setRemark("备件更换出库");
            if(StringUtils.isNotEmpty(partReplacedto.getDealDate())){
                pDTO.setStorageTime(partReplacedto.getDealDate());
            }else {
                pDTO.setStorageTime(partReplacedto.getRepDate());
            }
            try {
                this.iPartStorageRecordService.savepartStorage(pDTO,userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}else {
			//插入备件更换信息
			PartReplace partReplace = new PartReplace();
			partReplace.setPkId(BaseUtil.getUUID());
			partReplace.setEquipId(partReplacedto.getEquipId());
			partReplace.setRepUser(partReplacedto.getRepUser());
			partReplace.setRepReason(partReplacedto.getRepReason());
			partReplace.setRepNum(partReplacedto.getRepNum());
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date0;
			try {
				if(partReplacedto.getRepDate()==null) {
					partReplace.setRepDate(new Date());
				}else {
					date0 = df.parse(partReplacedto.getRepDate());
					partReplace.setRepDate(date0);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}  
			partReplace.setCreateDate(new Date());
			partReplace.setRemark(partReplacedto.getRemark());
			partReplace.setPartId(partReplacedto.getPartId());
			//保存更换信息
			iPartReplaceDao.insert(partReplace);
            //新备件自动进行出库操作
            SysUser sysUser = BaseUtil.getCurrentUser();
            String userId = sysUser.getPkId();
            PartStorageSaveDTO pDTO = new PartStorageSaveDTO();
            pDTO.setStorageNum(partReplacedto.getRepNum());
            ModelPart mp = iModelPartDao.selectById(partReplacedto.getPartId());
            pDTO.setPartId(mp.getPartId());//更换备件的id
            if(StringUtils.isNotEmpty(partReplacedto.getDealUser())){
                pDTO.setPickUser(partReplacedto.getDealUser());//故障处理人及为领料人
            }else {
                pDTO.setPickUser(partReplacedto.getRepUser());//领料人
            }
            pDTO.setRemark("备件更换出库");
            if(StringUtils.isNotEmpty(partReplacedto.getDealDate())){
                pDTO.setStorageTime(partReplacedto.getDealDate());
            }else {
                pDTO.setStorageTime(partReplacedto.getRepDate());
            }
            try {
                this.iPartStorageRecordService.savepartStorage(pDTO,userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
		}
		
	}
	@Override
	public PageInfo<PartReplace> listModelPartByFilter(String equipCode, String search, Filter filter) {
        if(StringUtils.isBlank(equipCode))
            return new PageInfo<>(new ArrayList<>());
        List<PartReplace> list = this.beforeList(IPartReplaceDao.class,filter).listModelPartByFilter(equipCode,search);
        PageInfo<PartReplace> page = new PageInfo<>(list);
        return page;
	}
	@Override
	public PartReplace getKeyPartByPartId(String equipCode, String partId,String localtionId, Filter filter) {
		PartReplace partReplace =iPartReplaceDao.getKeyPartByPartId(equipCode,partId,localtionId);
		return partReplace;
	}

}
